import * as commonService from '../services/CommonCRUD';
import * as otherService from '../services/other';
import * as workflow from '../services/workflow';
import { notification } from 'antd';
import * as common from '../utils/common'

export default {
    namespace: "COMP_JC",
    state: {
        list: [],
        flowList: [],
        total: null,
        page: 1,
        pageSize: 20,
        isEditChange: false,
        showEdit: false,
        showSeek: false,
        showStep: false,
        record: {},
        sortor: {},
        filters: {},
        seeks: [],
        keyName: "ID",
        permID: 7114,
        selectedRowKeys: [],
        visibleFilterName: null,
        frid: 0,
        flowRunInfo: {},
        folwExecutor: {},
    },
    reducers: {
        save(state, { payload: { data: list, total, page, pageSize, sorter, filters, selectedRowKeys, seeks, permID } }) {
            if (!sorter) {
                sorter = {}
            }
            if (!filters) {
                filters = {}
            }
            if (!seeks) {
                seeks = []
            }
            const visibleFilterName = null
            return { ...state, list, total, page, pageSize, sorter, filters, selectedRowKeys, visibleFilterName, seeks, permID };
        },
        saveFlowList(state, { payload: { flowList } }) {
            return { ...state, flowList };
        },
        setSelectedRowKeys(state, { payload: { selectedRowKeys } }) {
            return { ...state, selectedRowKeys };
        },
        setFilter(state, { payload: { colName, filter } }) {
            const filterVal = { [colName]: filter }
            const filters = { ...state.filters, ...filterVal }
            return { ...state, filters }
        },
        setVisibleFilterName(state, { payload: { visibleFilterName } }) {
            return { ...state, visibleFilterName };
        },
        setFrid(state, { payload: { frid } }) {
            return { ...state, frid };
        },
        updateRecord(state, { payload: { keys } }) {
            let record = { ...state.record, ...keys }
            return { ...state, record };
        },
        setRecord(state, { payload: { record } }) {
            return { ...state, record };
        },
        openEdit(state, { payload: { key } }) {
            let record = {}
            let index = -1
            if (key) {
                const { list, keyName } = state
                for (let i = 0; i < list.length; i++) {
                    if (list[i][keyName] === key) {
                        index = i;
                        break;
                    }
                }
                record = list[index]
            }
            const showEdit = true;
            const editIndex = index;

            return { ...state, showEdit, editIndex, record };
        },
        hideEdit(state) {
            const showEdit = false;
            return { ...state, showEdit };
        },
        hideStep(state) {
            const showStep = false;
            return { ...state, showStep };
        },
        editChange(state) {
            const isEditChange = true;
            return { ...state, isEditChange };
        },
        saveRecord(state, { payload: { record, runInfo, executor } }) {
            return { ...state, record, flowRunInfo: runInfo, folwExecutor: executor };
        },
        saveFlowRunInfo(state, { payload: { runInfo, runID } }) {
            return { ...state, flowRunInfo: runInfo, frid: runID, showStep: true };
        },
        saveFolwExecutor(state, { payload: { executor } }) {
            return { ...state, folwExecutor: executor };
        },
        saveCunm(state, { payload: { cunm } }) {
            const record = { ...state.record, CUNM: cunm }
            return { ...state, record };
        },
    },
    effects: {
        *fetch({ payload: { daoName, page, pageSize, sorter, filters, seeks, colName, filter, permID } }, { select, call, put }) {
            try {
                const mName = "COMP_JC"
                const m = yield select(state => state[mName]);
                filters = filters === undefined ? m.filters : filters;
                seeks = seeks === undefined ? m.seeks : seeks;
                page = page === undefined ? m.page : page;
                pageSize = pageSize === undefined ? m.pageSize : pageSize;
                sorter = sorter === undefined ? m.sorter : sorter;
                permID = permID === undefined ? m.permID : permID;
                if (colName !== undefined && filter !== undefined) {
                    const filterVal = { [colName]: filter }
                    let newFilters = { ...filters, ...filterVal }
                    if (filter === null) {
                        delete newFilters[colName]
                    }
                    filters = newFilters
                }
                let whereCauses = common.filtersTowhereCauses(filters)
                whereCauses = [...whereCauses, ...seeks]
                const orderItems = common.sorterToOrderItems(sorter)
                const listData = yield call(commonService.fetch, { daoName, page, pageSize, sorter: orderItems, filters: whereCauses, permID });
                const selectedRowKeys = []
                if (listData) {
                    yield put({
                        type: 'save',
                        payload: {
                            data: listData.Objectlist,
                            total: listData.Count,
                            page: parseInt(page),
                            pageSize: parseInt(pageSize),
                            sorter, filters, selectedRowKeys,
                            seeks, permID
                        },
                    });
                }
            } catch (e) {
                // console.log(e)
            }
        },
        *fetchFlowRunInfo({ payload: { runID } }, { call, put }) {
            const runInfo = yield call(workflow.getFolwRunInfo, { runID });
            if (runInfo) {
                yield put({
                    type: 'saveFlowRunInfo',
                    payload: {
                        runInfo, runID
                    },
                });
            }
        },
        *fetchFolwExecutor({ payload: { runID, stepID } }, { call }) {
            const executor = yield call(workflow.getFolwExecutor, { runID, stepID });
            if (executor) {
                yield put({
                    type: 'save',
                    payload: {
                        executor
                    },
                });
            }
        },
        *setFolwExecutor({ payload: { runID, stepID, userIDstr } }, { call }) {
            const frid = yield call(workflow.setFolwExecutor, { runID, stepID, userIDstr });
            if (frid) {
                notification.success({
                    message: `提示`,
                    description: "设置执行人成功！",
                })
            }
        },
        *flowCreate({ payload: { wfid, userID } }, { call, put }) {
            const ret = yield call(workflow.create, { wfid, userID });
            if (ret) {
                const frid = ret.runID
                if (frid) {
                    yield put({ type: 'fetchFlowRunInfo', payload: { runID: frid } });
                }
            }
        },
        *flowBatchSubmit({ payload: { runIDs, userID, desc, bType, rwIDs } }, { call, put }) {
            const ishld = 0
            let whereCauses = [{
                WhereItems: [{
                    FieldName: "RWID",
                    Operator: "=",
                    FieldValues: "" + rwIDs[0],
                }],
                RelationSign: "AND"
            }];
            const listData2 = yield call(commonService.fetch, { daoName: 'COMP_JC_MX', page: 1, pageSize: 100, filters: whereCauses, permID: 7114 });
            if (listData2.Count > 0) {
                const ret = yield call(workflow.batchSubmit, { runIDs, userID, desc, bType, ishld });
                if (ret) {
                    yield put({ type: 'reload', payload: { daoName: "COMP_JC" } });
                    yield put({ type: 'FlowDoingSum/fetch', payload: { daoName: "FlowDoingSum" } });
                    notification.success({
                        message: `提示`,
                        description: "流程提交成功！",
                    })
                }
            } else {
                notification.error({
                    message: `提示`,
                    description: "流程提交失败！，请录入监测项目",
                })
            }
        },
        *flowSubmit({ payload: { runID, userID, desc, bType } }, { call }) {
            const ret = yield call(workflow.submit, { runID, userID, desc, bType });
            if (ret) {
                notification.success({
                    message: `提示`,
                    description: "流程提交成功！",
                })
            }
        },
        *flowSendBack({ payload: { runID, userID, backStepID, desc } }, { call }) {
            const ret = yield call(workflow.sendBack, { runID, userID, backStepID, desc });
            if (ret) {
                notification.success({
                    message: `提示`,
                    description: "流程退回成功！",
                })
            }
        },
        *flowAbort({ payload: { runIDs } }, { call, put }) {
            const ret = yield call(workflow.abort, { runIDs });
            if (ret) {
                yield put({ type: 'reload', payload: { daoName: "COMP_JC" } });
                yield put({ type: 'FlowDoingSum/fetch', payload: { daoName: "FlowDoingSum" } });
                notification.success({
                    message: `提示`,
                    description: "流程已中止！",
                })
            }
        },
        *flowDelete({ payload: { runID } }, { call, put }) {
            const ret = yield call(workflow.deleteFolw, { runID });
            if (ret) {
                yield put({ type: 'reload', payload: { daoName: "COMP_JC" } });
                yield put({ type: 'FlowDoingSum/fetch', payload: { daoName: "FlowDoingSum" } });
                notification.success({
                    message: `提示`,
                    description: "流程删除成功！",
                })
            }
        },
        *exportData({ payload: { daoName, columnHeaders, permID } }, { select, call }) {
            try {
                const m = yield select(state => state[daoName]);
                const whereCauses = common.filtersTowhereCauses(m.filters)
                const orderItems = common.sorterToOrderItems(m.sorter)
                const data = yield call(commonService.exporData, { daoName, whereCauses, orderItems, columnHeaders, permID });
                if (data) {
                    let a = document.createElement('a');
                    let url = window.URL.createObjectURL(data);
                    a.href = url;
                    a.download = "数据导出.xlsx";
                    document.body.appendChild(a)
                    a.click()
                    setTimeout(function () { document.body.removeChild(a) }, 1000)
                    window.URL.revokeObjectURL(url);
                }
            } catch (e) {
                console.log(e) 
                throw e
            }
        },
        *remove({ payload: { daoName, keys } }, { select, call, put }) {
            if (keys.length === 0) {
                return
            }
            let ret
            if (keys.length > 1) {
                ret = yield call(commonService.removeKeys, { daoName, keys });
            } else {
                const m = yield select(state => state[daoName]);
                let values = null
                for (let i = 0; i < m.list.length; i++) {
                    if (keys[0] === m.list[i][m.keyName]) {
                        values = m.list[i]
                        break
                    }
                }
                ret = yield call(commonService.removeEntity, { daoName, values });
            }
            if (ret) {
                yield put({ type: 'reload', payload: { daoName } });
                yield put({ type: 'FlowDoingSum/fetch', payload: { daoName: "FlowDoingSum" } });
            }
        },
        *patch({ payload: { daoName, values } }, { call, put }) {
            const ret = yield call(commonService.patch, { daoName, values });
            if (ret) {
                yield put({ type: 'setRecord', payload: { record: values } });
                yield put({ type: 'reload', payload: { daoName } });
                notification.success({
                    message: `提示`,
                    description: "数据保存成功！"
                })
            }
        },
        *create({ payload: { daoName, values } }, { call, put }) {
            const ret = yield call(commonService.create, { daoName, values });
            if (ret) {
                const record = { ...values, ...ret }
                yield put({ type: 'setRecord', payload: { record } });
                yield put({ type: 'reload', payload: { daoName } });
                notification.success({
                    message: `提示`,
                    description: "数据添加成功！"
                })
            }
        },
        *reload({ payload: { daoName } }, { put, select }) {
            try {
                const { page, sorter, pageSize, filters } = yield select(state => state[daoName]);
                yield put({ type: 'fetch', payload: { daoName, page, pageSize, sorter, filters } });
            } catch (e) {
                console.log(e)
            }
        },
        *reloadWithFilters({ payload: { daoName, colName, filter } }, { put, select }) {
            const { page, sorter, pageSize, filters, record } = yield select(state => state[daoName]);
            const filterVal = { [colName]: filter }
            let newFilters = { ...filters, ...filterVal }
            if (!filter) {
                delete newFilters[colName]
            }
            yield put({ type: 'fetch', payload: { daoName, page, pageSize, sorter, filters: newFilters } });
        },
        *submitData({ payload: { daoName, datas } }, { call, put, select }) {
            const { keyName } = yield select(state => state[daoName]);
            let newDatas = datas, updateDatas = [], deleteDatas = []
            const keys = yield call(commonService.submitDatas, { daoName, newDatas, updateDatas, deleteDatas });
            yield put({ type: 'FlowDoingSum/fetch', payload: { daoName: "FlowDoingSum" } });
            notification.success({
                message: `提示`,
                description: "数据保存成功！",
            })
        },
        *clearFilter({ payload: { modelName, daoName } }, { put, select }) {
            const mName = modelName ? modelName : daoName
            const { page, sorter, pageSize } = yield select(state => state[mName]);
            yield put({ type: 'fetch', payload: { modelName, daoName, page, pageSize, sorter, filters: {} } });
        },
    },
};
